
package com.wisdom.collect.modbus.io;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public class FastByteArrayInputStream extends InputStream {

    private static final Logger logger = LoggerFactory.getLogger(FastByteArrayInputStream.class);

    protected int count;

    int pos;

    int mark;

    byte[] buf;

    FastByteArrayInputStream(byte[] buffer) {
        buf = buffer;
        count = buffer.length;
        pos = 0;
        mark = 0;
    }

    @Override
    public int read() throws IOException {
        logger.debug("read()");
        logger.debug("count={} pos={}", count, pos);
        return (pos < count) ? (buf[pos++] & 0xff) : (-1);
    }

    @Override
    public int read(byte[] toBuf) throws IOException {
        logger.debug("read(byte[])");
        return read(toBuf, 0, toBuf.length);
    }

    @Override
    public int read(byte[] toBuf, int offset, int length) throws IOException {
        logger.debug("read(byte[],int,int)");
        int avail = count - pos;
        if (avail <= 0) {
            return -1;
        }
        if (length > avail) {
            length = avail;
        }
        for (int i = 0; i < length; i++) {
            toBuf[offset++] = buf[pos++];
        }
        return length;
    }

    @Override
    public long skip(long count) {
        int myCount = (int) count;
        if (myCount + pos > this.count) {
            myCount = this.count - pos;
        }
        pos += myCount;
        return myCount;
    }

    @Override
    public int available() {
        return count - pos;
    }

    public int getCount() {
        return count;
    }

    @Override
    public void mark(int readlimit) {
        logger.debug("mark()");
        mark = pos;
        logger.debug("mark={} pos={}", mark, pos);
    }

    @Override
    public void reset() {
        logger.debug("reset()");
        pos = mark;
        logger.debug("mark={} pos={}", mark, pos);
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    // --- end ByteArrayInputStream compatible methods ---

    public byte[] toByteArray() {
        byte[] toBuf = new byte[count];
        System.arraycopy(buf, 0, toBuf, 0, count);
        return toBuf;
    }

    public synchronized byte[] getBufferBytes() {
        byte[] dest = new byte[count];
        System.arraycopy(buf, 0, dest, 0, dest.length);
        return dest;
    }

    public int getBufferOffset() {
        return pos;
    }

    public int getBufferLength() {
        return count;
    }

}
